/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.swagger.config;

import lombok.Setter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 注册 path
 *
 * @author zeng
 */
public class OpenAPIMetadataRegister implements InitializingBean, ApplicationContextAware {

  private ApplicationContext applicationContext;

  @Setter private String path;

  /**
   * 设置应用程序上下文
   *
   * @param applicationContext 应用程序上下文
   * @throws BeansException 可能抛出的异常
   */
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
  }

  /** 在属性设置后执行的初始化方法 */
  @Override
  public void afterPropertiesSet() {
    // 获取ServiceInstance实例
    String[] serviceInstanceNames = applicationContext.getBeanNamesForType(ServiceInstance.class);
    if (serviceInstanceNames.length == 0) {
      return;
    }
    ServiceInstance serviceInstance =
        applicationContext.getBean(serviceInstanceNames[0], ServiceInstance.class);
    // 设置元数据
    serviceInstance.getMetadata().put("spring-doc", path);
  }
}
